package demo.zzz.com.scancode;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.example.qrcode.Constant;
import com.example.qrcode.ScannerActivity;
import com.google.zxing.BarcodeFormat;
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Set;

import cn.bertsir.zbar.QrConfig;
import cn.bertsir.zbar.QrManager;
import cn.bingoogolapple.qrcode.core.BGAQRCodeUtil;
import demo.zzz.com.scancode.zbar.CaptureActivity;

public class MainActivity extends AppCompatActivity {
    private static final String TAG="MainActivity";
    private static final int RESULT_REQUEST_CODE = 200;
    private static final int REQUEST_CODE_SCAN = 100;


    private Button hello,ZBar,YZxing,ZBarLibary,BarView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_main );
        BGAQRCodeUtil.setDebug(true);

        hello = findViewById( R.id.hello );
        hello.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String appId = ""; // 填应用AppId AppConfig.WEIXIN_APP_ID
                IWXAPI api = WXAPIFactory.createWXAPI(MainActivity.this, appId);

                WXLaunchMiniProgram.Req req = new WXLaunchMiniProgram.Req();
                req.userName = "wx787668e06455492c"; // 填小程序原始id AppConfig.WEIXIN_XIAOCHENGXU_ID
                req.path = "/pages/index/index?kx=kxx"; //拉起小程序页面的可带参路径，不填默认拉起小程序首页
                req.miniprogramType = WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE;// 可选打开 开发版，体验版和正式版
                api.sendReq(req);
//                try {
//                    Intent intent = MainActivity.this.getPackageManager().getLaunchIntentForPackage("com.tencent.mm");
//                    intent.putExtra("LauncherUI.From.Scaner.Shortcut", true);
//                    MainActivity.this.startActivity(intent);
//
//                } catch (Exception e) {
//                    Toast.makeText( MainActivity.this,"没有安装微信",Toast.LENGTH_SHORT ).show();
//                }
                
            }
        } );

        ZBar = findViewById( R.id.ZBar );
        ZBar.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ContextCompat.checkSelfPermission( MainActivity.this, Manifest.permission.CAMERA ) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions( MainActivity.this, new String[]{Manifest.permission.CAMERA}, 2 );
                }else {
                    goScan();
                }
            }
        } );

        YZxing = findViewById( R.id.YZxing );
        YZxing.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ContextCompat.checkSelfPermission( MainActivity.this, Manifest.permission.CAMERA ) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions( MainActivity.this, new String[]{Manifest.permission.CAMERA}, 1 );
                }else {
                    // Have gotten the permission
                    startCaptureActivityForResult();
                }

            }
        } );

        ZBarLibary = findViewById( R.id.ZBarLibary );
        ZBarLibary.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startScan();
            }
        } );

        BarView = findViewById( R.id.BarView );
        BarView.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,BarViewActivity.class );
                startActivity(intent);
            }
        } );
    }

    /**
     * 跳转到扫码界面扫码
     */
    private void goScan(){
        Intent intent = new Intent(MainActivity.this, CaptureActivity.class);
        startActivityForResult(intent, REQUEST_CODE_SCAN);
    }

    private void  startScan(){
        QrConfig qrConfig = new QrConfig.Builder()
                .setDesText("(识别二维码)")//扫描框下文字
                .setShowDes(false)//是否显示扫描框下面文字
                .setShowLight(true)//显示手电筒按钮
                .setShowTitle(true)//显示Title
                .setShowAlbum(false)//显示从相册选择按钮
                .setCornerColor( Color.WHITE)//设置扫描框颜色
                .setLineColor(Color.WHITE)//设置扫描线颜色
                .setLineSpeed(QrConfig.LINE_MEDIUM)//设置扫描线速度
                .setScanType(QrConfig.TYPE_ALL)//设置扫码类型（二维码，条形码，全部，自定义，默认为二维码）
                .setScanViewType(QrConfig.SCANVIEW_TYPE_QRCODE)//设置扫描框类型（二维码还是条形码，默认为二维码）
                .setPlaySound(true)//是否扫描成功后bi~的声音
                .setTitleText("扫描二维码")//设置Tilte文字
                .setTitleBackgroudColor(Color.BLUE)//设置状态栏颜色
                .setTitleTextColor(Color.BLACK)//设置Title文字颜色
                .setAutoZoom(true)//是否自动调整焦距
                .setFingerZoom(false)//是否开始双指缩放
                .setScreenOrientation(QrConfig.SCREEN_PORTRAIT)//设置屏幕方向
                .setDoubleEngine(true)//是否开启双引擎识别(仅对识别二维码有效，并且开启后只识别框内功能将失效)
                .setLooperScan(false)//是否连续扫描二维码
                .create();

        QrManager.getInstance().init(qrConfig).startScan(MainActivity.this, new QrManager.OnScanResultCallback() {
            @Override
            public void onScanSuccess(String result) {
                Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
            }
        });
    }
    
    private void startCaptureActivityForResult() {
        Intent intent = new Intent(MainActivity.this, ScannerActivity.class);
        //这里可以用intent传递一些参数，比如扫码聚焦框尺寸大小，支持的扫码类型。
        //设置扫码框的宽
        intent.putExtra( Constant.EXTRA_SCANNER_FRAME_WIDTH, 400);
        //设置扫码框的高
        intent.putExtra(Constant.EXTRA_SCANNER_FRAME_HEIGHT, 400);
        //设置扫码框距顶部的位置
        intent.putExtra(Constant.EXTRA_SCANNER_FRAME_TOP_PADDING, 100);
        //设置是否启用从相册获取二维码(默认为FALSE，不启用)。
        intent.putExtra(Constant.EXTRA_IS_ENABLE_SCAN_FROM_PIC,true);

        startActivityForResult(intent, RESULT_REQUEST_CODE);

    }

    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult( requestCode, permissions, grantResults );
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    startCaptureActivityForResult();
                } else {
                    Toast.makeText( MainActivity.this, "拒绝", Toast.LENGTH_LONG ).show();
                }
            case 2:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    goScan();
                } else {
                    Toast.makeText( MainActivity.this, "拒绝", Toast.LENGTH_LONG ).show();
                }
            default:
                break;
        }

    }

    // 扫码onActivityResult
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult( requestCode, resultCode, data );

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case RESULT_REQUEST_CODE:
                    if (data == null) return;
                    String type = data.getStringExtra(Constant.EXTRA_RESULT_CODE_TYPE);
                    String content = data.getStringExtra(Constant.EXTRA_RESULT_CONTENT);
                    Toast.makeText(MainActivity.this,"codeType:" + type
                            + "-----content:" + content,Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;

            }
        }

        switch (requestCode) {
            case REQUEST_CODE_SCAN:
                // 扫描二维码回传
                if (resultCode == RESULT_OK) {
                    if (data != null) {
                        //获取扫描结果
                        Bundle bundle = data.getExtras();
                        String result = bundle.getString(CaptureActivity.EXTRA_STRING);
                        AlertDialog.Builder builder = new AlertDialog.Builder(this);
                        builder.setCancelable( false );
                        builder.setTitle("提示")
                                .setMessage("铅封号：" + recode(result))
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {

                                    }
                                })
                                .setNegativeButton( "取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {

                                    }
                                } )
                                .create().show();
                    }
                }
                break;
            default:
                break;
        }
        
    }

    //防止二维码扫描中文乱码
    private String recode(String str) {
        String formart = "";

        try {
            boolean ISO = Charset.forName("ISO-8859-1").newEncoder()
                    .canEncode(str);
            if (ISO) {
                formart = new String(str.getBytes("ISO-8859-1"), "GB2312");
            } else {
                formart = str;
            }
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return formart;
    }
}
